package com.bee.plus.market.controller;

import com.bee.plus.common.R;
import com.bee.plus.dto.ContentReq;
import com.bee.plus.market.service.MarketAiService;
import com.bee.plus.util.JsonUtil;
import com.bee.plus.vo.ChatContentVo;
import com.bee.plus.vo.ChatMessageVo;
import com.bee.plus.vo.ChatResponseVo;
import com.bee.plus.vo.ModelType;
import io.reactivex.Flowable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xupei
 */
@RestController
@RequestMapping("/market")
public class MarketController {


    private Logger logger= LoggerFactory.getLogger(MarketController.class);

    @Autowired
    private MarketAiService marketAiService;

    @GetMapping("/sayHello")
    public String sayHello(){
        return "ok";
    }


    @PostMapping("/chat")
    public R<ChatResponseVo> chat(@RequestBody ChatMessageVo messageVo){
        logger.info("start {}",messageVo.toString());
        ChatResponseVo chatResponseVo=marketAiService.chat(messageVo);
        logger.info("end {}",chatResponseVo.toString());
        return R.data(chatResponseVo);
    };


    @GetMapping(value = "/chatStream", produces = "text/event-stream")
    public Flux<ChatResponseVo> chatStream(String chatType,String content,Long conversationId){
        if(chatType==null){
            return Flux.empty();
        }

        ChatMessageVo messageVo=new ChatMessageVo();
        messageVo.setModelType(ModelType.getTypeName(chatType));
        ChatContentVo contentReq=new ChatContentVo();
        contentReq.setContent(content);
        contentReq.setRole("user");
        messageVo.setConversationId(conversationId!=null&&conversationId.compareTo(0L)>0?conversationId:null);
        List<ChatContentVo> messageList=new ArrayList();
        messageList.add(contentReq);
        messageVo.setMessages(messageList);
        logger.info("start {} {}",Thread.currentThread().getId(),messageVo.toString());
        Flowable<ChatResponseVo> chatResponseVoFlowable=marketAiService.chatStream(messageVo);
        logger.info("end {}",chatResponseVoFlowable);
        return Flux.from(chatResponseVoFlowable);
    };

    @PostMapping("/storeChatMessage/{conversationId}/{modelType}")
    public R storeChatMessage(@RequestBody ChatResponseVo responseVo,
                              @PathVariable("conversationId")  String conversationId,@PathVariable("modelType") String modelType){
        responseVo.setConversationId(conversationId);
        responseVo.setModelType(ModelType.getTypeName(modelType));
        marketAiService.storeChatMessage(responseVo);
        return R.data("success");
    }
}
